<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of report
 *
 * @author Константин Охотник
 */
class StorageModel extends Crud
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('ci_access');
    }
    
/*=========================Вывод всех продуктов===============================*/
    public function getProduct($url, $per_page)
    {
        $config['base_url']=$url;
        $config['total_rows'] = $this->db->count_all('tb_product');
        $config['per_page'] = $per_page;
        $this->pagination->initialize($config);
        $r = $this->db->query('SELECT * FROM tb_product order by id desc LIMIT '.(int)$this->uri->segment(3).', '. (int)$config['per_page']);
        $i = 0;
        foreach($r =$r->result_array() as $key )
        {
           $p = $this->get_one('tb_person', 'id', $key['id_person']);
           if(empty($p))
           {
                $r[$i]['person'] = 'Пользователь удалён';
           }
           else
           {
                $r[$i]['person'] = $p[0]['name'].' '.$p[0]['first_name'].' '.$p[0]['second_name'];
           }
           $p = $this->get_one('gl_categories', 'id', $key['id_category']);
           $r[$i]['category'] = $p[0]['name'];
           $p = $this->get_one('tb_fabricator', 'id', $key['id_fabricator']);
           $r[$i]['fabricator'] = $p[0]['name'];
           $i++;
        }
        return $r;
    }

/*============================список категорий================================*/    
    public function Category()
    {
        return $this->get_array('gl_categories');    
    }
    
/*============================список производителей===========================*/     
    public function Fabricator()
    {
        return $this->get_array('tb_fabricator');    
    }
    
/*============================Удаление продукта===============================*/    
    public function Delete($cell)
    {
        $this->delete_post('tb_product', 'id', $cell);
    }

/*===========================Добавление нового продукта=======================*/     
    public function Add($arr)
    {
        $arr['id_person'] = $_SESSION['userdata']['1'];
        $arr['date'] = date('Y-m-d');
        if($arr['fabricator']!='')
        {
           $this->add_db('tb_fabricator', array('name'=>$arr['fabricator']));
           $id_fabricator = $this->get_one('tb_fabricator', 'name', $arr['fabricator']);
           $arr['id_fabricator'] = $id_fabricator[0]['id'];
        }
        unset($arr['fabricator']);
        return $this->add_db('tb_product', $arr);
    }

/*=============================Добавление параметров==========================*/     
    public function AddParams($tb, $id1=false, $id2=false)
    {
        $params[0]['id'] = '0';
        $params[0]['name'] = 'Выбрать';
        
        if($id1&&$id2)
        {
            $resp = $this->db->get_where($tb, array('id_category'=>$id1,'id_fabricator'=>$id2));
            $params = array_merge($params, $resp->result_array());
        }
        else
        {
            $params = array_merge($params, $this->get_array($tb));
        }
        return $params;
    }
    
/*=================================Поиск клиента==============================*/      
    public function Filter($url, $request, $per_page)
    {
        $offers = 0;                                //Для limit $offers, $num
        if (isset($request['per_page']))
        {
            $offers = (int)$request['per_page'];
            unset($request['per_page']); 
        }
        foreach($request as $key=>$value)
        {
            if($value=='')
            {
               unset($request[$key]);
            }
        }
        $selcount =  $this->_CountRowsQuery('SELECT COUNT(*) FROM tb_product WHERE ', $request);
        $seldata  =  $this->_CountRowsQuery('SELECT * FROM tb_product WHERE ', $request);
        $num_rows = $this->numRowsTender($selcount);
        
        if($num_rows == 0)
        {
            $query['error'] = "По вашему запросу ничего не найдено";
            return $query;
        }
        
        $config['base_url']=$url.'?'.http_build_query($request);
        $config['total_rows'] = $num_rows;
        $config['per_page'] = $per_page;
        $config['page_query_string'] = TRUE;
        $this->pagination->initialize($config);
       
        $r = $this->_getFilterTenders($seldata, $config['per_page'],$offers);
        
        $i = 0;
        foreach($r  as $key )
        {
           $p = $this->get_one('tb_person', 'id', $key['id_person']);
            if(empty($p))
           {
                $r[$i]['person'] = 'Пользователь удалён';
           }
           else
           {
                $r[$i]['person'] = $p[0]['name'].' '.$p[0]['first_name'].' '.$p[0]['second_name'];
           }
           $p = $this->get_one('gl_categories', 'id', $key['id_category']);
           $r[$i]['category'] = $p[0]['name'];
           $p = $this->get_one('tb_fabricator', 'id', $key['id_fabricator']);
           $r[$i]['fabricator'] = $p[0]['name'];
           $i++;
        }
        return  $r;
    }

/*================================Построение запроса==========================*/     
    private function _CountRowsQuery($select, $request)
    {
        $idcategory="";
        $count = 0;
        foreach($request as $key =>$value)
        {
            if ($key =='id_category')
            {
                $select.= " id_category ='".$request[$key]."'";
            }
            if($key == 'id_fabricator')
            {
               $select.= " id_fabricator ='".$request[$key]."'";
            }

            if ($count <(count($request)-1))
            {
                $select.=" AND ";
            }
            $count++;
        }
        return $select;
    }
    
/*===================================Кол записей==============================*/      
    private function numRowsTender($str)
    {
        $query= $this->db->query($str)->result();
        $arr =(array)$query[0];
        return (integer)$arr['COUNT(*)'];
    }
    
/*===================================Вывод====================================*/       
    private function _getFilterTenders($select, $num, $offset= 0)
    {
        $offset = (int)$offset;
        $select .= " ORDER BY id DESC LIMIT  $offset , $num";
        $query = $this->db->query($select);
        return (array)$query->result_array();
    }
        
}